#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QFileDialog>
#include <QEvent>
#include <QKeyEvent>

QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

public slots:
    /**
     * 选择图片后显示在Label中
     */
    void openFiles(){
        picIndex = 0;
        files = QFileDialog::getOpenFileNames();
        if(files.size() > 0){
            QString fileName = files[0];
            label->setText(fileName);
            QPixmap pix(fileName);
            label->setPixmap(pix);
        }
    }
    /**
     * 显示下一张图片
     */
    void showRight(){
        if(picIndex+1 < files.length()){
            picIndex++;
        }else{
            picIndex = 0;
        }

        QPixmap pix(files[picIndex]);
        label->setPixmap(pix);
        label->setFocus();
    }

    void showLeft(){
        if(picIndex > 0){
            picIndex--;
        }else{
            picIndex=0;
        }
        QPixmap pix(files[picIndex]);
        label->setPixmap(pix);
        label->setFocus();
    };

    bool eventFilter(QObject *watched, QEvent *event){
        if(watched == label){

            if(event->type() == QEvent::KeyPress){
                QKeyEvent *keyEvent = static_cast<QKeyEvent*> (event);
                if(keyEvent->key() == Qt::Key_Left){
                    showLeft();
                }else if(keyEvent->key() == Qt::Key_Right){
                    showRight();
                }
                return true;
            }
        }
        return QWidget::eventFilter(watched, event);
    }

private:
    Ui::Widget *ui;
    QPushButton *leftBtn,*rightBtn,*openBtn;
    QLabel *label;
    QStringList files;
    int picIndex;
};
#endif // WIDGET_H
